#
# Encoder.py
#
# This work is released under the GNU GPL, version 2 or later.
#
from Utils.kdeemul import *
from Utils.Paths import *
from Utils.Settings import *
from Player import *
from MP3EncoderProcess import *
from OggEncoderProcess import *
from WavEncoderProcess import *

class Encoder(QObject):
	def __init__(self):
		QObject.__init__(self)
		self.tracksToEncode = []
		self.encodeProcess = None
		self.settings = Settings.settings()
		self.encodeTotal = 0
		self.encodeIndex =0
		from DB.EncoderLibrary import  EncoderLibrary
		self.encoderLibrary = EncoderLibrary.singleton()
		self.encoderPlaylist = self.encoderLibrary.playlistWithName("Encoder")

	def encodeTrack(self,track):
		self.encodeTracks([track])

	def encodeTracks(self,tracks):
		if len(tracks)>0:
			if not self.encoderPlaylist.hasTracks()==0:
				self.encodeTotal = 0
				self.encodeIndex =0
			eTracks = []
			for track in tracks:
				from EncoderLibrary import  EncoderTrack
				eTrack = EncoderTrack()
				eTrack.copyFieldsFrom(track)
				eTrack.trackID = self.encoderLibrary.uniqueTrackID()
				self.encoderLibrary.addTrack(eTrack)
				eTracks.append(eTrack)
			self.encoderPlaylist.addTracks(eTracks)
			self.encodeTotal = self.encodeTotal+len(tracks)
			if self.settings.get("Encoding",True):
				self.encodeNextTrack()

	def encodeNextTrack(self):
		#print "encoding next track"
		if (self.encodeProcess==None or not self.encodeProcess.isRunning()):
			if self.encoderPlaylist.hasTracks():
				self.gotStatus(None,{'Source':'Encoder','Status':'Begin'})
				self.encodeIndex = self.encodeIndex+1
				self.track = self.encoderPlaylist.firstTrack()
				if os.path.exists(self.track.originalLocation):
					encoder = Settings.settings().get('Encoder','mp3')
					if encoder=='mp3':
						self.encodeProcess = MP3EncoderProcess(self.track,self.encodeIndex,self.encodeTotal)
					elif encoder=='ogg':
						self.encodeProcess = OggEncoderProcess(self.track,self.encodeIndex,self.encodeTotal)
					elif encoder=='wav':
						self.encodeProcess = WavEncoderProcess(self.track,self.encodeIndex,self.encodeTotal)
					QObject.connect(self.encodeProcess,PYSIGNAL("done"),self.endEncodeTrack)
					QObject.connect(self.encodeProcess,PYSIGNAL("status"),self.gotStatus)
					self.encodeProcess.run()
				else:
					self.endEncodeTrack() # should delete this entry, then advance
			else:
				self.gotStatus(None,{'Source':'Encoder','Status':'End'})
		else:
			pass
			#print "encoding is busy!"
			
	def endEncodeTrack(self,process = None):
		#print "done encoding",process.track.title
		self.encoderLibrary.removeTrackIDsFromAllPlaylists([self.track.trackID])
		self.encoderLibrary.killTrackIDs([self.track.trackID])
		self.encodeProcess = None
		if not process or not process.interrupted:
			self.encodeNextTrack()

	def gotStatus(self,process,status):
		if status.has_key('Track'):
			status['Track'].setRipStatus(status)
		self.emit(PYSIGNAL('status'),(status,None))
		
	def isEncoding(self):
		if self.encodeProcess and self.encodeProcess.isRunning(): return True
		return False
	
	def killEncoder(self):
		if self.encodeProcess:
			self.encodeProcess.kill()
			self.encodeProcess = None
			self.gotStatus(None,{'Source':'Encoder','Status':'End'})

	def static_singleton():
		global _encoderSingleton
		if _encoderSingleton==None:
			_encoderSingleton = Encoder()
		return _encoderSingleton

	singleton = staticmethod(static_singleton)
	
	def static_killCurrentEncoder():
		Encoder.singleton().killEncoder()
	killCurrentEncoder = staticmethod(static_killCurrentEncoder)

_encoderSingleton = None
